<template>
  <view class="container">
    <!-- 头部 -->
    <view class="header">
      <text class="title">新增Banner</text>
    </view>

    <!-- 表单内容 -->
    <view class="form">
      <view class="form-item">
        <text class="label">Banner名称</text>
        <input 
          v-model="formData.title" 
          class="input" 
          placeholder="请输入Banner名称"
          maxlength="50"
        />
        <text class="char-count">{{ formData.title?.length || 0 }}/50</text>
      </view>

      <view class="form-item">
        <text class="label">Banner图片</text>
        <view class="image-upload-section">
          <!-- 图片上传方式选择 -->
          <view class="upload-method-selector">
            <text class="method-label">上传方式：</text>
            <radio-group class="radio-group" @change="handleUploadMethodChange">
              <label class="radio-item">
                <radio value="url" :checked="uploadMethod === 'url'" />
                <text class="radio-text">URL地址</text>
              </label>
              <label class="radio-item">
                <radio value="upload" :checked="uploadMethod === 'upload'" />
                <text class="radio-text">上传图片</text>
              </label>
            </radio-group>
          </view>

          <!-- URL地址方式 -->
          <view v-if="uploadMethod === 'url'" class="url-upload-section">
            <view class="url-input-group">
              <input 
                v-model="imageUrl" 
                class="input" 
                placeholder="请输入图片URL地址"
              />
              <button class="add-image-btn" @click="addImageFromUrl">添加图片</button>
            </view>
            <text class="hint">建议使用网络图片URL，如：https://example.com/image.jpg</text>
            <view v-if="imageUrl && imageUrl.trim() !== ''" class="image-preview">
              <image 
                :src="imageUrl" 
                class="preview-image"
                mode="aspectFill"
                @error="handleImageError"
              />
              <text class="preview-url">{{ imageUrl }}</text>
            </view>
          </view>

          <!-- 上传图片方式 -->
          <view v-if="uploadMethod === 'upload'" class="file-upload-section">
            <uni-file-picker
              v-model="uploadedFile"
              file-mediatype="image"
              limit="1"
              :image-styles="imageStyles"
              @select="handleFileSelect"
              @delete="handleFileDelete"
            >
              <button class="upload-btn">选择图片</button>
            </uni-file-picker>
            <text class="hint">支持JPG、PNG格式，建议尺寸：750x300px</text>
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="label">跳转链接类型</text>
        <radio-group class="radio-group" @change="handleLinkTypeChange">
          <label class="radio-item">
            <radio value="0" :checked="formData.link_type === '0'" />
            <text class="radio-text">无跳转</text>
          </label>
          <label class="radio-item">
            <radio value="1" :checked="formData.link_type === '1'" />
            <text class="radio-text">外部链接</text>
          </label>
          <label class="radio-item">
            <radio value="2" :checked="formData.link_type === '2'" />
            <text class="radio-text">应用内页面</text>
          </label>
        </radio-group>
        <text class="hint">选择Banner点击后的跳转行为</text>
      </view>

      <view class="form-item">
        <text class="label">跳转链接</text>
        <input 
          v-model="formData.link_value" 
          class="input" 
          :disabled="formData.link_type === '0'"
          :placeholder="getLinkPlaceholder()"
        />
        <text class="hint">
          {{ getLinkHint() }}
        </text>
      </view>

      <view class="form-row">
        <view class="form-item half">
          <text class="label">排序</text>
          <input 
            v-model="formData.sort" 
            class="input" 
            type="number"
            placeholder="0"
          />
          <text class="hint">数字越小越靠前</text>
        </view>

        <view class="form-item half">
          <text class="label">状态</text>
          <view class="radio-group">
            <label class="radio-item">
              <radio 
                value="1" 
                :checked="formData.status === 1"
                @click="formData.status = 1"
              />
              <text class="radio-text">启用</text>
            </label>
            <label class="radio-item">
              <radio 
                value="0" 
                :checked="formData.status === 0"
                @click="formData.status = 0"
              />
              <text class="radio-text">禁用</text>
            </label>
          </view>
        </view>
      </view>

    </view>

    <!-- 操作按钮 -->
    <view class="actions">
      <button class="btn cancel" @click="handleCancel">取消</button>
      <button class="btn submit" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'

// 响应式数据
const formData = reactive({
  title: '',
  image: null,
  link_type: '0',
  link_value: '',
  sort: 0,
  status: 1
})

const loading = ref(false)
const imageUrl = ref('')
const uploadMethod = ref('url') // 上传方式：url或upload
const uploadedFile = ref(null)
const imageStyles = ref({
  width: '100%',
  height: '300rpx',
  border: {
    color: '#e9ecef',
    width: '2rpx',
    style: 'solid',
    radius: '12rpx'
  }
})

// 图片上传方式切换
const handleUploadMethodChange = (event) => {
  uploadMethod.value = event.detail.value
  // 切换方式时清空图片数据
  formData.image = null
  imageUrl.value = ''
  uploadedFile.value = null
}

// 从URL添加图片
const addImageFromUrl = () => {
  if (!imageUrl.value || imageUrl.value.trim() === '') {
    uni.showToast({
      title: '请输入图片URL地址',
      icon: 'none'
    })
    return
  }
  
  // 简单的URL格式验证
  if (!imageUrl.value.startsWith('http://') && !imageUrl.value.startsWith('https://')) {
    uni.showToast({
      title: '请输入有效的URL地址（以http://或https://开头）',
      icon: 'none'
    })
    return
  }
  
  formData.image = {
    url: imageUrl.value.trim(),
    type: 'url'
  }
  uni.showToast({
    title: '图片URL已添加',
    icon: 'success'
  })
}

// 文件选择处理
const handleFileSelect = (event) => {
  const file = event.tempFiles[0]
  if (file) {
    // 这里需要实现文件上传逻辑
    // 暂时使用临时URL作为预览
    formData.image = {
      url: file.path,
      name: file.name,
      size: file.size,
      type: 'upload'
    }
  }
}

// 文件删除处理
const handleFileDelete = () => {
  formData.image = null
  uploadedFile.value = null
}

// 图片加载错误处理
const handleImageError = () => {
  uni.showToast({
    title: '图片加载失败，请检查URL是否正确或是否存在防盗链',
    icon: 'none'
  })
}

// 跳转链接类型变更处理
const handleLinkTypeChange = (event) => {
  const newLinkType = event.detail.value
  formData.link_type = newLinkType
  
  // 如果选择无跳转，清空链接值
  if (newLinkType === '0') {
    formData.link_value = ''
  }
}

// 状态变更处理
const handleStatusChange = (event) => {
  formData.status = parseInt(event.detail.value)
}

// 获取链接输入框占位符
const getLinkPlaceholder = () => {
  switch (formData.link_type) {
    case '1':
      return '请输入外部链接地址（如：https://example.com）'
    case '2':
      return '请输入应用内页面路径（如：/pages/index/index）'
    default:
      return '请先选择跳转链接类型'
  }
}

// 获取链接提示信息
const getLinkHint = () => {
  switch (formData.link_type) {
    case '1':
      return '外部链接必须以http://或https://开头'
    case '2':
      return '应用内页面路径格式如：/pages/index/index'
    default:
      return '选择"无跳转"时，用户点击Banner不会进行任何跳转'
  }
}

// 表单验证
const validateForm = () => {
  if (!formData.title || formData.title.trim() === '') {
    uni.showToast({
      title: '请输入Banner名称',
      icon: 'none'
    })
    return false
  }
  
  if (formData.title.trim().length > 50) {
    uni.showToast({
      title: 'Banner名称不能超过50个字符',
      icon: 'none'
    })
    return false
  }
  
  if (!formData.image || !formData.image.url) {
    uni.showToast({
      title: '请添加Banner图片',
      icon: 'none'
    })
    return false
  }
  
  // 跳转链接验证
  if (formData.link_type === '1') {
    if (!formData.link_value || formData.link_value.trim() === '') {
      uni.showToast({
        title: '请输入外部链接地址',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.link_value.startsWith('http://') && !formData.link_value.startsWith('https://')) {
      uni.showToast({
        title: '外部链接必须以http://或https://开头',
        icon: 'none'
      })
      return false
    }
  } else if (formData.link_type === '2') {
    if (!formData.link_value || formData.link_value.trim() === '') {
      uni.showToast({
        title: '请输入应用内页面路径',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.link_value.startsWith('/')) {
      uni.showToast({
        title: '应用内页面路径必须以/开头',
        icon: 'none'
      })
      return false
    }
  }
  
  if (formData.sort < 0) {
    uni.showToast({
      title: '排序值不能为负数',
      icon: 'none'
    })
    return false
  }
  
  return true
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) return
  
  loading.value = true
  
  try {
    // 准备提交数据
    const submitData = {
      title: formData.title.trim(),
      image: formData.image,
      link_type: parseInt(formData.link_type),
      link_value: formData.link_type === '0' ? '' : formData.link_value.trim(),
      sort: parseInt(formData.sort) || 0,
      status: formData.status
    }
    
    const result = await uniCloud.callFunction({
      name: 'food-banners',
      data: {
        action: 'add-banner',
        data: {
          bannerData: submitData
        }
      }
    })
    
    if (result.result.code === 200) {
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      })
      
      // 延迟跳转到list页面，让用户看到成功提示
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/banners/list'
        })
      }, 500)
    } else {
      uni.showToast({
        title: result.result.message || '添加失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('提交失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消添加吗？所有未保存的更改将丢失。',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack()
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 32rpx;
}

.header {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.form {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 48rpx;
  position: relative;
  
  .label {
    display: block;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .input {
    width: 100%;
    height: 80rpx;
    border: 2rpx solid #e9ecef;
    border-radius: 12rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    background: #ffffff;
    
    &:focus {
      border-color: #007aff;
      outline: none;
    }
    
    &::placeholder {
      color: #999;
    }
  }
  
  .textarea {
    width: 100%;
    min-height: 160rpx;
    border: 2rpx solid #e9ecef;
    border-radius: 12rpx;
    padding: 24rpx;
    font-size: 28rpx;
    background: #ffffff;
    resize: none;
    
    &:focus {
      border-color: #007aff;
      outline: none;
    }
    
    &::placeholder {
      color: #999;
    }
  }
  
  .char-count {
    position: absolute;
    right: 0;
    bottom: -32rpx;
    font-size: 24rpx;
    color: #999;
  }
  
  .hint {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
  }
}

.form-row {
  display: flex;
  gap: 32rpx;
  
  .form-item.half {
    flex: 1;
  }
}

.url-input-group {
  display: flex;
  gap: 16rpx;
  align-items: center;
  
  .input {
    flex: 1;
  }
  
  .add-image-btn {
    width: 160rpx;
    height: 80rpx;
    background: #007aff;
    color: #ffffff;
    border: none;
    border-radius: 8rpx;
    font-size: 26rpx;
    white-space: nowrap;
    
    &:active {
      background: #0056cc;
    }
  }
}

.image-preview {
  margin-top: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  
  .preview-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 12rpx;
    border: 2rpx solid #e9ecef;
  }
  
  .preview-url {
    font-size: 24rpx;
    color: #666;
    word-break: break-all;
    background: #f8f9fa;
    padding: 16rpx;
    border-radius: 8rpx;
    border: 1rpx solid #e9ecef;
  }
}

.radio-group {
  display: flex;
  gap: 48rpx;
  
  .radio-item {
    display: flex;
    align-items: center;
    gap: 12rpx;
    
    .radio-text {
      font-size: 26rpx;
      color: #333;
    }
  }
}

/* 图片上传相关样式 */
.image-upload-section {
  .upload-method-selector {
    display: flex;
    align-items: center;
    gap: 24rpx;
    margin-bottom: 24rpx;
    
    .method-label {
      font-size: 26rpx;
      font-weight: bold;
      color: #333;
    }
    
    .radio-group {
      gap: 32rpx;
    }
  }
  
  .url-upload-section {
    .url-input-group {
      display: flex;
      gap: 16rpx;
      align-items: center;
      
      .input {
        flex: 1;
      }
      
      .add-image-btn {
        width: 160rpx;
        height: 80rpx;
        background: #007aff;
        color: #ffffff;
        border: none;
        border-radius: 8rpx;
        font-size: 26rpx;
        white-space: nowrap;
        
        &:active {
          background: #0056cc;
        }
      }
    }
  }
  
  .file-upload-section {
    .upload-btn {
      width: 100%;
      height: 80rpx;
      background: #f8f9fa;
      color: #333;
      border: 2rpx dashed #e9ecef;
      border-radius: 12rpx;
      font-size: 26rpx;
      
      &:active {
        background: #e9ecef;
      }
    }
  }
}

.image-preview {
  margin-top: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  
  .preview-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 12rpx;
    border: 2rpx solid #e9ecef;
  }
  
  .preview-url {
    font-size: 24rpx;
    color: #666;
    word-break: break-all;
    background: #f8f9fa;
    padding: 16rpx;
    border-radius: 8rpx;
    border: 1rpx solid #e9ecef;
  }
}

.actions {
  display: flex;
  gap: 32rpx;
  margin-top: 64rpx;
  
  .btn {
    flex: 1;
    height: 88rpx;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: bold;
    
    &.cancel {
      background: #f8f9fa;
      color: #666;
      border: 2rpx solid #e9ecef;
      
      &:active {
        background: #e9ecef;
      }
    }
    
    &.submit {
      background: #007aff;
      color: #ffffff;
      
      &:active {
        background: #0056cc;
      }
    }
  }
}

/* 响应式适配 */
@media (max-width: 750rpx) {
  .container {
    padding: 24rpx;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-item.half {
    margin-bottom: 32rpx;
  }
}
</style>